package com.xuexi.demos.utils;


import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    // 排除路径
    private static final String[] EXCLUDE_PATHS = {
            "/api/user/login",
            "/api/user/register", 
            "/api/user/wxlogin",
            "/api/open"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // 获取请求路径
        String requestURI = request.getRequestURI();

        // 检查排除路径
        for (String path : EXCLUDE_PATHS) {
            if (requestURI.startsWith(path)) {
                return true;
            }
        }

        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");

        // 验证头部格式
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            sendError(response, "缺少认证令牌");
            return false;
        }

        // 提取令牌
        String token = authHeader.substring(7);

        // 验证令牌
        String username = SimpleJwtUtils.parseToken(token);
        if (username == null) {
            sendError(response, "无效的令牌");
            return false;
        }

        // 将用户名存储到请求中
        request.setAttribute("username", username);
        return true;
    }

    private void sendError(HttpServletResponse response, String message) throws Exception {
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("{\"code\": 401, \"error\": \"" + message + "\"}");
        out.flush();
    }
}